package com.qing.utils

import com.mongodb.MongoClient
import com.mongodb.client.MongoCollection
import org.bson.Document
import org.codehaus.jettison.json.{JSONArray, JSONObject}


/**
  * Created by wuliao on 2017/12/29.
  */
object MongodbUtils {

  // 连接到数据库
  val mongoClient = new MongoClient("175.102.18.112", 27018)

  def getModelCollection(): MongoCollection[Document] = {

    val mongoDatabase = mongoClient.getDatabase("simple_ml")
    mongoDatabase.getCollection("model")
  }

  def getModelList(name: String): JSONObject = {
    val collection = getModelCollection()
    val document = new Document("name", name)
    val it = collection.find(document).iterator()

    val json = new JSONObject()
    val array = new JSONArray()

    val ret = it.next()
    if (ret != null) {
      val map = ret.entrySet()
      val tempIt = map.iterator()
      val tempObj = new JSONObject()
      while (tempIt.hasNext) {
        val e = tempIt.next()
        tempObj.put(e.getKey, e.getValue)
      }
      array.put(tempObj)
    }
    json.put("data", array)
  }


  def getModelById(id: String): JSONObject = {
    val collection = getModelCollection()
    val document = new Document("_id", id)
    val it = collection.find(document).iterator()

    val json = new JSONObject()
    val ret = it.next()
    if (ret != null) {
      val map = ret.entrySet()
      val tempIt = map.iterator()
      while (tempIt.hasNext) {
        val e = tempIt.next()
        json.put(e.getKey, e.getValue)
      }
    }
    json
  }

}


